package com.system.shiro.credentials;


import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.SecurityUtils;

import com.common.utils.StringUtils;
import com.common.utils.WebUtils;

public class SessionFilter implements Filter {
	
	private String excludeURI;
	
	private String[] excludeURIs;
	
	@Override
	public void destroy() {

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {		
		HttpServletRequest httpServletRequest = WebUtils.toHttp(request);
		HttpServletResponse httpServletResponse = WebUtils.toHttp(response);
		if (!SecurityUtils.getSubject().isAuthenticated()) {
			boolean isExcludeURI = false;
			String servletPath = httpServletRequest.getServletPath();
			for(String uri : excludeURIs){
				uri = StringUtils.replaceBlank(uri);
				if(uri.equals(servletPath)){
					isExcludeURI = true;
					break;
				}
			}
			if(isExcludeURI){
				filterChain.doFilter(httpServletRequest, httpServletResponse);
				return;
			}
			if (httpServletRequest.getHeader("x-requested-with") != null && httpServletRequest.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")) {
				httpServletResponse.setHeader("sessionstatus", "timeout"); // 在响应头设置session状态
				return ;
			}
		}
		filterChain.doFilter(request, response);
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		excludeURI = filterConfig.getInitParameter("excludeURI");
		if (!StringUtils.isBlank(excludeURI)) {
			excludeURIs = excludeURI.split(",");
		}
		return;
	}

}
